package org.jeecg.modules.fw.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;
import org.jeecg.modules.fw.entity.FwRoomExamine;
import org.jeecg.modules.fw.service.IFwRoomExamineService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.rooms.Enum.RoomStatusEnum;
import org.jeecg.modules.rooms.entity.CesRooms;
import org.jeecg.modules.rooms.service.CesRoomsServiceImpl;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: fw_room_examine
 * @Author: jeecg-boot
 * @Date:   2023-05-23
 * @Version: V1.0
 */
@Api(tags="fw_room_examine")
@RestController
@RequestMapping("/fw/fwRoomExamine")
@Slf4j
public class FwRoomExamineController extends JeecgController<FwRoomExamine, IFwRoomExamineService> {
	@Autowired
	private IFwRoomExamineService fwRoomExamineService;
	@Resource
	private IBusRoomsLivingOrderService busRoomsLivingOrderService;
	@Resource
	private CesRoomsServiceImpl cesRoomsService;
	@Resource
	private IBusLivingCustomerService busLivingCustomerService;
	@Resource
	private IBusCustomerService busCustomerService;
	@Resource
	private IBusWaiterService busWaiterService;

	 @Resource
	 private SysBaseApiImpl sysBaseAPI;
	 @Resource
	 private ISysUserService sysUserService;
	 @Resource
	 private IBusHotelService busHotelService;

	/**
	 * 分页列表查询
	 *
	 * @param fwRoomExamine
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "fw_room_examine-分页列表查询")
	@ApiOperation(value="fw_room_examine-分页列表查询", notes="fw_room_examine-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<FwRoomExamine>> queryPageList(FwRoomExamine fwRoomExamine,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FwRoomExamine> queryWrapper = QueryGenerator.initQueryWrapper(fwRoomExamine, req.getParameterMap());
		Page<FwRoomExamine> page = new Page<FwRoomExamine>(pageNo, pageSize);
		IPage<FwRoomExamine> pageList = fwRoomExamineService.page(page, queryWrapper);
		pageList.getRecords().forEach(t -> {
			CesRooms cesRooms = cesRoomsService.getById(t.getRoomId());
			if (cesRooms != null) {
				t.setRoomName(cesRooms.getName());
				RoomStatusEnum roomStatusEnum = RoomStatusEnum.val(cesRooms.getRoomStatus());
				if (roomStatusEnum != null) {
					t.setRoomStatus(roomStatusEnum.getTitle());
				}
				BusRoomsLivingOrder busRoomsLivingOrder = busRoomsLivingOrderService.getById(t.getLivingOrderId());
				if (busRoomsLivingOrder != null) {
					t.setArriveTime(busRoomsLivingOrder.getArrivalTime());
					t.setDueOutTime(busRoomsLivingOrder.getDueOutTime());
					BusCustomer busCustomer = busCustomerService.getById(busRoomsLivingOrder.getContactId());
					if (busCustomer != null) {
						t.setContactName(busCustomer.getName());
						t.setContactPhone(busCustomer.getPhone());
					}
				}
				BusWaiter busWaiter=busWaiterService.getById(t.getWaiterId());
				if (busWaiter != null) {
					t.setCfWaiterName(busWaiter.getName());
				}
			}
		});
		return Result.OK(pageList);
	}


	/**
	 *   添加
	 *
	 * @param fwRoomExamine
	 * @return
	 */
	@AutoLog(value = "fw_room_examine-添加")
	@ApiOperation(value="fw_room_examine-添加", notes="fw_room_examine-添加")
	//@RequiresPermissions("fw:fw_room_examine:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody FwRoomExamine fwRoomExamine) {
		fwRoomExamineService.save(fwRoomExamine);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param fwRoomExamine
	 * @return
	 */
	@AutoLog(value = "fw_room_examine-编辑")
	@ApiOperation(value="fw_room_examine-编辑", notes="fw_room_examine-编辑")
	//@RequiresPermissions("fw:fw_room_examine:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody FwRoomExamine fwRoomExamine) {
		fwRoomExamineService.updateById(fwRoomExamine);
		return Result.OK("编辑成功!");
	}

	 @AutoLog(value = "查房操作")
	 @ApiOperation(value="查房操作", notes="查房操作")
	 @RequestMapping(value = "/checkRoom", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> checkRoom(@RequestBody FwRoomExamine fwRoomExamine) {
		 switch (fwRoomExamine.getState()) {
			 case 1:
				 fwRoomExamine.setPromoterTime(DateTime.now());
				 fwRoomExamine.setPromoterBy(TokenUtils.getAuthUser().getRealname());
				 break;
			 case 3:
				 fwRoomExamine.setCompletedTime(DateTime.now());
				 fwRoomExamine.setCompletedBy(TokenUtils.getAuthUser().getRealname());
				 /*添加消息通知*/
				 BusHotel busHotel = busHotelService.getById(fwRoomExamine.getHotelId());
				 LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				 lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
				 lambdaQueryWrapper.eq(SysUser::getRelTenantIds, busHotel.getTenantId());
				 List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper);
				 String userIds = "";
				 for (SysUser sysUser : sysUsers) {
					 userIds += sysUser.getUsername() + ",";
				 }
				 if (!userIds.isEmpty()) {
					 MessageDTO messageDTO = new MessageDTO();
					 messageDTO.setFromUser("");
					 messageDTO.setToUser(userIds);
					 messageDTO.setTenantId(busHotel.getTenantId());
					 messageDTO.setTitle(fwRoomExamine.getRoomName() + "查房完毕");
					 messageDTO.setContent(fwRoomExamine.getRoomName() + "查房完毕");
					 messageDTO.setCategory(CommonConstant.MSG_CATEGORY_1);
					 messageDTO.setMsgCategoryDetail(CommonConstant.MSG_ROOM);
					 sysBaseAPI.sendSysAnnouncement(messageDTO);
				 }
				 break;
		 }
		 fwRoomExamineService.updateById(fwRoomExamine);
		 return Result.OK("查房操作成功!");
	 }

	 /**
	  * 找出已申请查房，尚未查房完毕的房间
	  */
	 //@AutoLog(value = "fw_room_examine-分页列表查询")
	 @ApiOperation(value="fw_room_examine-找出已申请查房，尚未查房完毕的房间", notes="fw_room_examine-找出已申请查房，尚未查房完毕的房间")
	 @GetMapping(value = "/getExamineRoom")
	 public Result<List<String>> getExamineRoom(String hotel) {
		 return Result.OK(service.getExamineRoom(hotel));
	 }

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "fw_room_examine-通过id删除")
	@ApiOperation(value="fw_room_examine-通过id删除", notes="fw_room_examine-通过id删除")
	//@RequiresPermissions("fw:fw_room_examine:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		fwRoomExamineService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "fw_room_examine-批量删除")
	@ApiOperation(value="fw_room_examine-批量删除", notes="fw_room_examine-批量删除")
	//@RequiresPermissions("fw:fw_room_examine:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fwRoomExamineService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "fw_room_examine-通过id查询")
	@ApiOperation(value="fw_room_examine-通过id查询", notes="fw_room_examine-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FwRoomExamine> queryById(@RequestParam(name="id",required=true) String id) {
		FwRoomExamine fwRoomExamine = fwRoomExamineService.getById(id);
		if(fwRoomExamine==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(fwRoomExamine);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fwRoomExamine
    */
    //@RequiresPermissions("fw:fw_room_examine:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FwRoomExamine fwRoomExamine) {
        return super.exportXls(request, fwRoomExamine, FwRoomExamine.class, "fw_room_examine");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("fw:fw_room_examine:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FwRoomExamine.class);
    }

}
